package com.yhw.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yhw.common.exception.Assert;
import com.yhw.common.result.ResponseEnum;
import com.yhw.srb.core.enums.BorrowInfoStatusEnum;
import com.yhw.srb.core.enums.BorrowerStatusEnum;
import com.yhw.srb.core.enums.LendStatusEnum;
import com.yhw.srb.core.enums.UserBindEnum;
import com.yhw.srb.core.mapper.*;
import com.yhw.srb.core.pojo.entity.*;
import com.yhw.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.yhw.srb.core.pojo.vo.BorrowerDetailVO;
import com.yhw.srb.core.service.BorrowInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhw.srb.core.service.BorrowerService;
import com.yhw.srb.core.service.DictService;
import com.yhw.srb.core.service.LendService;
import com.yhw.srb.core.util.LendNoUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author yhw
 * @since 2022-08-29
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private IntegralGradeMapper integralGradeMapper;

    @Resource
    private DictService dictService;

    @Resource
    private BorrowerMapper borrowerMapper;

    @Resource
    private BorrowerService borrowerService;

    @Resource
    private LendService lendService;

    @Override
    public BigDecimal getBorrowAmount(Long userId) {   // 获取借款额度

        //获取用户积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);  //  ResponseEnum.LOGIN_MOBILE_ERROR(208, "用户不存在"),
        Integer integral = userInfo.getIntegral();

        //根据积分查询借款额度
        LambdaQueryWrapper<IntegralGrade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(IntegralGrade::getIntegralStart,integral)   // IntegralGrade::getIntegralStart <=
                    .ge(IntegralGrade::getIntegralEnd,integral);    // IntegralGrade::getIntegralStart >=
        IntegralGrade integralGrade = integralGradeMapper.selectOne(queryWrapper);

        if(integralGrade == null){   // 积分过高 或 过低
            return new BigDecimal("0");
        }

        return integralGrade.getBorrowAmount();
    }

    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {

        //获取userInfo的用户数据
        UserInfo userInfo = userInfoMapper.selectById(userId);

        /*
            后端也要校验一下数据的 防止恶意用户绕过前端 用恶意数据向后端发请求
            1. 首先 想要借款  就得先绑卡 也就是绑定第三支付平台（也就是hfb）
            2. 绑卡了  你还要认证一下你借款人信息(也就是房和车这些财产信息)
            3. 借款数额 不能超过 你的额度
         */

        //判断用户绑定状态
        Assert.isTrue(
                userInfo.getBindStatus().intValue() == UserBindEnum.BIND_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_BIND_ERROR);

        //判断用户的借款人信息是否审批通过
        Assert.isTrue(
                userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_AMOUNT_ERROR);


        //判断借款额度是否足够
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        Assert.isTrue(
                borrowInfo.getAmount().doubleValue() <= borrowAmount.doubleValue(),
                ResponseEnum.USER_AMOUNT_LESS_ERROR);

        //存储数据
        borrowInfo.setUserId(userId);
        // 百分比要转成小数 (因为前端传过来的是一个整数，而数据库中存的是小数   比如 12%  我们此时拿到的是12  要12/100 存入数据库 )
        // Bigdecimal 不能直接 +-*/  要调用方法 add() subtract()  multiply()  divide()   abs()
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());   // CHECK_RUN(1, "审核中")

        baseMapper.insert(borrowInfo);
    }

    @Override
    public Integer getStatusByUserId(Long userId) {

        LambdaQueryWrapper<BorrowInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BorrowInfo::getUserId,userId)
                    .select(BorrowInfo::getStatus);
        List<Object> objects = baseMapper.selectObjs(queryWrapper);

        if(objects.size() == 0){
            //借款人尚未提交信息   NO_AUTH(0, "未认证"),
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }

        Integer status = (Integer)objects.get(0);

        return status;
    }

    @Override
    public List<BorrowInfo> selectList() {

        List<BorrowInfo> borrowInfoList = baseMapper.selectBorrowInfoList();

        for (BorrowInfo borrowInfo : borrowInfoList) {
            // 转换 数据  前端要的是字符串 这里的还是整数  需要转换一下
            String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
            String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
            String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());

            borrowInfo.getParam().put("returnMethod",returnMethod);
            borrowInfo.getParam().put("moneyUse",moneyUse);
            borrowInfo.getParam().put("status",status);
        }

        return borrowInfoList;
    }

    @Override
    public Map<String, Object> getBorrowInfoDetail(Long id) {

        // 获取 借款信息
        BorrowInfo borrowInfo = baseMapper.selectById(id);

        // 转换 数据  前端要的是字符串 这里的还是整数  需要转换一下
        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put("returnMethod",returnMethod);
        borrowInfo.getParam().put("moneyUse",moneyUse);
        borrowInfo.getParam().put("status",status);


        // 获取 借款人信息
        Long userId = borrowInfo.getUserId();
        LambdaQueryWrapper<Borrower> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Borrower::getUserId,userId);
        Borrower borrower = borrowerMapper.selectOne(queryWrapper);

        // 转换 数据  前端要的是字符串 这里的还是整数  需要转换一下
        BorrowerDetailVO borrowerDetailVOById = borrowerService.getBorrowerDetailVOById(borrower.getId());


        // 组装数据
        Map<String, Object> result = new HashMap<>();
        result.put("borrowInfo",borrowInfo);
        result.put("borrower",borrowerDetailVOById);

        return result;
    }

    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {

        // 修改 借款信息 状态
        Long borrowInfoId = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        baseMapper.updateById(borrowInfo);

        //审核通过则创建标的
        if (borrowInfoApprovalVO.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()) {
            //创建标的
            lendService.createLend(borrowInfoApprovalVO,borrowInfo);
        }

    }
}
